package com.ms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.dao.PlaceApplicationMapper;
import com.ms.entity.PlaceApplication;
import com.ms.entity.PlaceRecord;
import com.ms.service.inter.PlaceApplicationService;
import com.ms.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 场地申请服务实现类
 * 实现场地申请相关业务逻辑
 */
@Service
public class PlaceApplicationServiceImpl extends ServiceImpl<PlaceApplicationMapper, PlaceApplication> implements PlaceApplicationService {
    
    @Autowired
    private PlaceApplicationMapper placeApplicationMapper;
    
    /**
     * 保存场地申请
     * @param application 场地申请信息
     * @return 是否保存成功
     */
    @Override
    public boolean savePlaceApplication(PlaceApplication application) {
        // 检查日期冲突
        if (checkDateConflict(application.getPlId(), application.getStartDate(), application.getEndDate())) {
            throw new RuntimeException("申请的日期范围内存在已被占用的日期");
        }
        
        return save(application);
    }
    
    /**
     * 根据举办方ID查询场地申请记录
     * @param organizerId 举办方ID
     * @return 场地申请记录列表
     */
    @Override
    public List<PlaceApplication> getPlaceApplicationsByOrganizerId(Integer organizerId) {
        QueryWrapper<PlaceApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("or_id", organizerId);
        queryWrapper.orderByDesc("app_time");
        return list(queryWrapper);
    }
    
    /**
     * 检查指定场地在指定日期范围内是否已被占用
     * @param placeId 场地ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 是否存在冲突
     */
    @Override
    public boolean checkDateConflict(Integer placeId, Date startDate, Date endDate) {
        return placeApplicationMapper.checkDateConflict(placeId, startDate, endDate) > 0;
    }
    
    /**
     * 管理员审批场地申请
     * @param application 包含审批结果的申请信息
     * @return 是否审批成功
     */
    @Override
    public boolean approvePlaceApplication(PlaceApplication application) {
        // 获取当前登录的管理员信息
        com.ms.entity.Manager manager = UserContext.getManager();
        if (manager == null) {
            throw new RuntimeException("管理员未登录");
        }
        
        // 获取原始申请信息
        PlaceApplication originalApplication = getById(application.getLeaId());
        if (originalApplication == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        // 如果是通过审批，则生成场地记录
        if (application.getLeaStatus() != null && application.getLeaStatus() == 1) { // 1表示通过
            // 检查是否已经生成过记录
            if (placeApplicationMapper.checkIfRecordsExist(application.getLeaId()) > 0) {
                throw new RuntimeException("该申请已生成过场地记录");
            }
            
            // 生成场地记录
            generatePlaceRecords(originalApplication);
        }
        
        // 更新申请状态和审核意见
        originalApplication.setLeaStatus(application.getLeaStatus());
        originalApplication.setMaOpinion(application.getMaOpinion());
        
        return updateById(originalApplication);
    }
    
    /**
     * 根据场地申请信息生成场地记录
     * @param application 通过审批的场地申请
     * @return 是否生成成功
     */
    @Override
    public boolean generatePlaceRecords(PlaceApplication application) {
        // 获取开始日期和结束日期
        LocalDate startLocalDate = application.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate = application.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        
        // 计算日期范围内的天数
        long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
        
        // 生成每一天的记录
        List<PlaceRecord> records = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            LocalDate currentDate = startLocalDate.plusDays(i);
            Date currentDateAsDate = Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            
            PlaceRecord record = new PlaceRecord();
            record.setLeaId(application.getLeaId());
            record.setOrId(application.getOrId());
            record.setPlId(application.getPlId());
            record.setAppTime(currentDateAsDate);
            
            records.add(record);
        }
        
        // 批量保存记录
        return !records.isEmpty() && placeApplicationMapper.batchInsertPlaceRecords(records) == records.size();
    }
}